//
//  GBNetTool.m
//  GBNetWork
//
//  Created by Chen on 16/2/1.
//  Copyright © 2016年 Chen. All rights reserved.
//

#import "GBNetTool.h"
#import "AFHTTPSessionManager.h"
#import "SVProgressHUD.h"
#import "MBProgressHUD.h"
#import "GBHudUtil.h"
#import "AFNetworkActivityIndicatorManager.h"
#import "MJExtension.h"
#import "GTMBase64.h"
#import "GTMDefines.h"
#import "JSONKit.h"
#import "NSData+CommonCrypto.h"
#import "AFURLSessionManager.h"
//#import "RspCacheDAO.h"
#import "GJWBaseRequest.h"
#import "DesToHexString.h"
#import "GZIP.h"
#import "GBAlertView.h"
//#import "ASIDataCompressor.h"
#define JSON_BODY_REUEST   @"com.ailk.app.mapp.model.req.%@Request" //接口号类
#define JSON_KEY @"msg"
#define DES_KEY @"WOCF_DESKEY"
@interface GBNetTool(){
}
@property(nonatomic,strong)AFHTTPSessionManager *afmanger;
@end


@implementation GBNetTool

#pragma mark - 类方法
+(GBNetTool *)shareGBNetTool{
    static GBNetTool *share = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"GNNetTool 版本111");
        share = [[self alloc]init];
    });
    return share;
}



+(void)netGetAsyn:(GJWBaseRequest *)requestModel
          success:(ReqSuccess)sucess
          failure:(ReqFailure)failure
        operation:(GBNetToolOperation *)operation{
    
    [[self shareGBNetTool] netReqAsyncGet:requestModel
                                  success:sucess
                                  failure:failure
                                operation:operation];
}

+(void)netPostAsyn:(GJWBaseRequest *)requestModel
           success:(ReqSuccess)sucess
           failure:(ReqFailure)failure
         operation:(GBNetToolOperation *)operation{
    GBNetToolOperation *opt = operation? operation:[GBNetToolOperation defaultOperation];
    [[self shareGBNetTool] netPostAsyn:requestModel
                               success:sucess
                               failure:failure
                             operation:opt];
}

+(void)netDownLoadFile:(NSString*)urlStr
              progress:(DownLoadProgress)progress
                compet:(DownLoadCompletion)complet
             operation:(GBNetToolOperation *)operation{
    [[self shareGBNetTool] netDownLoadFile:urlStr
                                  progress:progress
                                    compet:complet
                                 operation:operation];
}
+(void)clearAllCache{
    [[self shareGBNetTool] clearAllCache];
}

#pragma mark - 内部函数
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.afmanger = [AFHTTPSessionManager manager];
        
        
    }
    return self;
}

/**
 *  设置AFNetWorking
 *
 *  @param requestModel 请求模型
 */
-(void)configManager:(GJWBaseRequest*)requestModel operation:(GBNetToolOperation *)operation{
    // 设置请求
    self.afmanger.operationQueue.maxConcurrentOperationCount = 10;
    self.afmanger.requestSerializer = [AFHTTPRequestSerializer serializer];
    //此部分内容头部写死
    [self.afmanger.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//    [self.afmanger.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    
    //此部分为用户
    //    NSLog(@"%@",requestModel.head.mj_keyValues);
//    for (NSString *key in requestModel.head.mj_keyValues.allKeys) {
//        [self.afmanger.requestSerializer setValue:[requestModel.head.mj_keyValues objectForKey:key] forHTTPHeaderField:key];
//    }
    self.afmanger.responseSerializer = [AFHTTPResponseSerializer serializer];
    self.afmanger.responseSerializer.acceptableContentTypes = [NSSet setWithArray:@[@"application/json",
                                                                                    @"text/html",
                                                                                    @"text/json",
                                                                                    @"text/plain",
                                                                                    @"text/javascript",
                                                                                    @"text/xml",
                                                                                    @"application/x-www-form-urlencoded",
                                                                                    @"image/*"]];
}

/**
 *  请求前的一些东动作
 *
 *  @param requestModel 请求模型
 *
 *  @return 是否准备好发送
 */
-(BOOL)readyToSend:(GJWBaseRequest*)requestModel
           success:(ReqSuccess)sucess
           failure:(ReqFailure)failure
        requstMode:(RequestMode)requestmode
          paramers:(NSDictionary*)paramers
         operation:(GBNetToolOperation *)operation{
    
    
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
    if (![self checkUrl:requestModel.baseUrl]) {
        [GBHudUtil hideHud];
        [GBHudUtil showhint:@"请求地址有误!" delay:2];
        return NO;
    };
    if (operation.showHud) {
        [GBHudUtil showHud:operation.hudText];
    }
    int reqRandom = (arc4random() % 501) + 500;
    if (operation.debugRequestMode&GBDebugzModeRequestAlert) {
     
        NSString *str = [NSString stringWithFormat:@"\n\n\n---------%@请求报文如下 start-tag:%d--------\n \n\n请求体body:\n%@\n\n---------%@请求报文如上 end-tag:%d--------\n\n\n",requestModel.head.bizCode,reqRandom, [requestModel  dicttionaryOfparmaters],requestModel.head.bizCode,reqRandom];
        [GBAlertView showAlertViewWith:@"请求报文" buttonTitle:nil message:str clickBlock:^BOOL(NSInteger *index) {
            return YES;
        }];
        
    }else if (operation.debugRequestMode & GBDebugzModeRequestConsole){
         NSLog(@"\n\n\n---------%@请求报文如下 start-tag:%d--------\n\n请求体body:\n%@\n\n---------%@请求报文如上 end-tag:%d--------\n\n\n",requestModel.head.bizCode,reqRandom,[requestModel dicttionaryOfparmaters],requestModel.head.bizCode,reqRandom);
    }
   
    if (operation.cachePolicy == CachePolicyNone) {
    }else if(operation.cachePolicy == CachePolicyPermanent){
        NSString *quryUrl = nil;
        if (requestmode == RequestModeGet) {
            
            quryUrl = requestModel.baseUrl;
//            quryUrl = [self makeUrl:requestModel paramers:paramers];
            
        }else{
            quryUrl = [self makeUrl:requestModel paramers:paramers];
            
        }
        NSDictionary *cache = [self getCacheWithUrl:quryUrl paramers:nil];
        int rspRandom = (arc4random() % 501) + 500;
        
        
        
        if (cache) {
            
            if (operation.debugResposeMode == GBDebugzModeResposeAlert||operation.debugResposeMode == GBDebugzModeResposeBoth) {
                NSString *str = [NSString stringWithFormat:@"\n\n\n---------%@返回cache报文如下 start-tag:%d--------\n\n%@\n\n---------%@返回cache报文如上 end-tag:%d--------\n\n\n",requestModel.head.bizCode,rspRandom,cache,requestModel.head.bizCode,rspRandom];
                [GBAlertView showAlertViewWith:@"请求报文" buttonTitle:nil message:str clickBlock:^BOOL(NSInteger *index) {
                    return YES;
                }];
            }
            
            if (operation.debugResposeMode == GBDebugzModeResposeConsole||operation.debugResposeMode == GBDebugzModeResposeBoth){
                LogRed(@"\n\n\n---------%@返回cache报文如下 start-tag:%d--------\n\n%@\n\n---------%@返回cache报文如上 end-tag:%d--------\n\n\n",requestModel.head.bizCode,rspRandom,cache,requestModel.head.bizCode,rspRandom);
            }
            [GBHudUtil hideHud];
            if (sucess) {
                sucess(cache);
            }
            return NO;
        }else{
            return YES;
        }
    }
    return YES;
}


-(NSString*)makeUrl:(GJWBaseRequest*)requestModel
           paramers:(NSDictionary*)paramers{
    NSMutableString *paramersStr = [[NSMutableString alloc]init];
    for (NSString* key in paramers.allKeys) {
        
        NSString *kvStr = [NSString stringWithFormat:@"&%@=%@",key,[paramers.allValues objectAtIndex:[paramers.allKeys indexOfObject:key]]];
        [paramersStr insertString:kvStr atIndex:paramersStr.length];
    }
    
    [paramersStr replaceCharactersInRange:NSMakeRange(0, 1) withString:@"?"];
    
    NSString *readstr = [NSString stringWithFormat:@"%@%@",requestModel.baseUrl,paramersStr];
    
    
    
    
    return [NSString stringWithUTF8String:[readstr UTF8String]];
}

/**
 *  请求成功处理函数
 *
 *  @param sucess         请求成功回调
 *  @param operation      AFHTTPRequestOperation
 *  @param responseObject AF返回的数据
 */
-(void)handleSuccess:(ReqSuccess)sucess
                task:(NSURLSessionDataTask * _Nonnull)task
      responseObject:(id)responseObject
           operation:(GBNetToolOperation *)operation
        requestModel:(GJWBaseRequest*)requestModel
            paramers:(NSDictionary*)paramers
{
    
    
    [GBHudUtil hideHud];
    int rspRandom = (arc4random() % 501) + 500;
    
    NSDictionary* bodyDict = [self makeRespose:responseObject operation:operation];
    
    if (operation.debugResposeMode == GBDebugzModeResposeAlert || operation.debugResposeMode == GBDebugzModeResposeBoth) {
        
        NSString *str = [NSString stringWithFormat:@"\n\n\n---------%@返回报文如下 start-tag:%d--------\n\n%@\n\n---------%@返回报文如上 end-tag:%d--------\n\n\n",requestModel.head.bizCode,rspRandom,[bodyDict mj_keyValues],requestModel.head.bizCode,rspRandom];
        
        [GBAlertView showAlertViewWith:@"返回报文" buttonTitle:nil message:str clickBlock:^BOOL(NSInteger *index) {
            return YES;
        }];
        
        
       
    }
    if (operation.debugResposeMode == GBDebugzModeResposeConsole||operation.debugResposeMode == GBDebugzModeResposeBoth){
        NSLog(@"\n\n\n---------%@返回报文如下 start-tag:%d--------\n\n%@\n\n---------%@返回报文如上 end-tag:%d--------\n\n\n",requestModel.head.bizCode,rspRandom,bodyDict,requestModel.head.bizCode,rspRandom);
        
    
        
    }
    //    NSString*rpstr = [task.response.URL.absoluteString stringByReplacingOccurrencesOfString:@"+" withString:@" "];
    //    NSString* result = [rpstr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    if (operation.cachePolicy == GBCachePolicyNone) {
        
    }else{
        
        NSString *curl = [self makeUrl:requestModel paramers:paramers];
        [self cacheUrl:curl paramers:bodyDict];
    }
    if (sucess) {
        sucess(bodyDict);
    }
    
    if (bodyDict) {
        [self saveCookie:bodyDict];
    }
    
    
}

-(void)saveCookie:(NSDictionary *)rspDict{
    [[NSUserDefaults standardUserDefaults] setObject:rspDict[@"header"][@"identityId"] == [NSNull null]?[NSNull null]:rspDict[@"header"][@"identityId"] forKey:@"sessionId"];
}

/**
 *  请求失败处理函数
 *
 *  @param failure   失败回调
 *  @param operation AFHTTPRequestOperation
 *  @param error     失败原因
 */
-(void)handleFalire:(ReqFailure)failure task:(NSURLSessionDataTask * _Nonnull)task error:(NSError*)error operation:(GBNetToolOperation *)operation{
    [GBHudUtil hideHud];
    
    int rspRandom = (arc4random() % 501) + 500;
    
    if (operation.debugResposeMode == GBDebugzModeResposeAlert || operation.debugResposeMode == GBDebugzModeResposeBoth) {
        
        NSString *str = [NSString stringWithFormat:@"\n\n\n---------请求出错了↓ start-tag:%d--------\n\n%@\n\n---------请求出错了↑ end-tag:%d--------\n\n\n",rspRandom,error,rspRandom];
        [GBAlertView showAlertViewWith:@"返回报文" buttonTitle:nil message:str clickBlock:^BOOL(NSInteger *index) {
            return YES;
        }];
        
        
        
    }
    if (operation.debugResposeMode == GBDebugzModeResposeConsole||operation.debugResposeMode == GBDebugzModeResposeBoth){
        NSLog(@"\n\n\n---------请求出错了↓ start-tag:%d--------\n\n%@\n\n---------请求出错了↑ end-tag:%d--------\n\n\n",rspRandom,error,rspRandom);
        
        
        
    }
    
    
    
    
    if (failure) {
        failure(task,error);
    }
}
-(void)netReqAsyncGet:(GJWBaseRequest*)requestModel
              success:(ReqSuccess)sucess
              failure:(ReqFailure)failure
            operation:(GBNetToolOperation *)operation{
    [self configManager:requestModel operation:operation];
    NSDictionary *paramers = [self makeParamters:requestModel
                                         success:sucess
                                         failure:failure
                                       operation:operation];
    BOOL ready = [self readyToSend:requestModel
                           success:sucess
                           failure:failure
                        requstMode:RequestModeGet paramers:paramers operation:operation];
    if(!ready)return;
    
    [self.afmanger GET:requestModel.baseUrl parameters:paramers progress:^(NSProgress * _Nonnull downloadProgress) {
        //        NSLog(@"get进度 %f ",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self handleSuccess:sucess task:task responseObject:responseObject operation:operation requestModel:requestModel paramers:paramers];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self handleFalire:failure task:task error:error operation:operation];
    }];
}





-(void)netPostAsyn:(GJWBaseRequest *)requestModel
           success:(ReqSuccess)sucess failure:(ReqFailure)failure
         operation:(GBNetToolOperation *)operation{
    [self configManager:requestModel operation:operation];
    NSDictionary *paramers = [[self makeParamters:requestModel
                                         success:sucess
                                         failure:failure
                                       operation:operation] mj_JSONObject];
    BOOL ready = [self readyToSend:requestModel
                           success:sucess
                           failure:failure
                        requstMode:RequestModePost
                          paramers:paramers
                         operation:operation];
    if(!ready)return;
    
    
    [self.afmanger POST:requestModel.baseUrl
             parameters:paramers
               progress:^(NSProgress * _Nonnull uploadProgress) {
               } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                   
                   
                   [self handleSuccess:sucess
                                  task:task
                        responseObject:responseObject
                             operation:operation
                          requestModel:requestModel
                              paramers:paramers];
               } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                   [self handleFalire:failure task:task error:error operation:operation];
               }];
}


-(void)netDownLoadFile:(NSString*)urlStr
              progress:(DownLoadProgress)progress
                compet:(DownLoadCompletion)complet
             operation:(GBNetToolOperation *)operation{
    
    MBProgressHUD *hud =nil;
    if (operation.showHud) {
        hud =[GBHudUtil showProgressWithText:operation.hudText];
    }
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
    NSURLSessionDownloadTask *downloadTask = [self.afmanger downloadTaskWithRequest:request
                                                                           progress:^(NSProgress * _Nonnull downloadProgress) {
                                                                               if (progress) {
                                                                                   if(hud)
                                                                                       hud.progress = 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
                                                                                   progress(downloadProgress,1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
                                                                               }
                                                                           } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
                                                                               NSURL *downloadURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
                                                                               return [downloadURL URLByAppendingPathComponent:[response suggestedFilename]];
                                                                           } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
                                                                               
                                                                               [NSData dataWithContentsOfURL:filePath];
                                                                               if (complet) {
                                                                                   complet(response,filePath,error);
                                                                               }
                                                                               if(hud)
                                                                                   hud.hidden = YES;
                                                                               
                                                                           }];
    [downloadTask resume];
}


-(NSDictionary*)makeParamters:(GJWBaseRequest *)requestModel
                      success:(ReqSuccess)sucess
                      failure:(ReqFailure)failure
                    operation:(GBNetToolOperation *)operation{
    
    if (operation.thirdServer) {
        
        
        
        return [requestModel dicttionaryOfparmaters];
    }else{
        return  operation.enCompres? [self baseCompress:requestModel operation:operation] : [NSDictionary dictionaryWithObject:[requestModel dicttionaryOfparmaters] forKey:JSON_KEY];
    }
}



/**
 *  对网络返回的数据进行处理
 *
 *  @param responseObject 原始网络数据
 *  @param operation      处理配置  如果是加密的报文 解密    如果是第三方不做任何处理
 *
 *  @return 经过处理后的数据 明文报文
 */
-(NSDictionary*)makeRespose:(id)responseObject
                  operation:(GBNetToolOperation *)operation{
   
    
    
    NSDictionary *dict = [(NSDictionary*)responseObject mj_keyValues];
    if (operation.thirdServer) {
        return [dict mj_keyValues];
    }else{
            NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            //二进制反序列
            NSData* base64Data = [GTMBase64 decodeData:responseObject];
            NSString* sourceStr = [[NSString alloc] initWithData:base64Data encoding:NSUTF8StringEncoding];
            //解压gzip
            NSData *decompressData = [base64Data gunzippedData];
            NSString* decompressStr = [[NSString alloc] initWithData:decompressData encoding:NSUTF8StringEncoding];
            NSString *string = [NSString stringWithString:decompressStr];
            NSDictionary *rspDict = (NSDictionary*)[string mj_JSONObject];
            return  rspDict ;
    }
}



#pragma mark - url操作
/**
 *  特殊字符转义
 *
 *  @param url 请求url
 *
 *  @return 转以后的url
 */
-(NSString *)URLEncode:(NSString *)url {
    NSString *urlStr =
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)url,
                                                              NULL,
                                                              CFSTR(":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`"), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)));
    if (urlStr) {
        return urlStr;
    }
    
    return url;
}
/**
 *  检查url是否有效
 *
 *  @param url url
 *
 *  @return 有效值
 */
-(BOOL)checkUrl:(NSString *)url{
    NSURL *ur = [NSURL URLWithString:url];
    if (ur) {
        return YES;
    }
    return NO;
}


#pragma mark - 类型转换
-(NSData*)base64EncodeDataWithDictionary:(NSDictionary*)data{
    if (!data) {
        return [NSData data];
    }
    return [GTMBase64 encodeData:[NSJSONSerialization dataWithJSONObject:data options:NSJSONWritingPrettyPrinted error:nil]];
}

-(NSDictionary*)dictionaryWithData:(NSData*)data{
    NSError *error;
    NSDictionary* json = [NSJSONSerialization
                          JSONObjectWithData:data
                          options:kNilOptions
                          error:&error];
    NSArray* latestLoans = [json objectForKey:@"loans"];
    return json;
}


-(NSString *)stringWithDictionary:(NSDictionary *)dic{
    if (!dic) {
        dic = [[NSDictionary alloc]init];
    }
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    NSMutableString * str1 = [[NSMutableString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSString* headerData=str1;
    headerData = [headerData stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];  //去除掉首尾的空白字符和换行字符
    headerData = [headerData stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    headerData = [headerData stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return headerData ;
}


-(NSString*)stringWithJsonDict:(NSDictionary*)dict{
    [dict JSONString];
    NSDictionary *dice = [[NSDictionary alloc]initWithObjectsAndKeys:@"fsdfa",@"fdfds", nil];
    NSString *bodyJSON = [[NSString alloc] initWithData:[dice JSONData]
                                               encoding:NSUTF8StringEncoding];
    return bodyJSON;
}





#pragma mark - 加密解密

/**
 *  json字符串编码
 *
 *  @param str Json
 *
 *  @return base64编码后的 字符串
 */
-(NSString*)stringWithBase64Encode:(NSString*)str{
    NSData* requestData = [str dataUsingEncoding:NSUTF8StringEncoding];
    NSString* base64Str = [GTMBase64 stringByEncodingData:requestData];
    return base64Str;
}


/**
 *  des加密 +base64 转码
 *
 *  @param plainText 需要加密的内容
 *  @param key       密钥
 *
 *  @return 加密后的内容
 */
- (NSString *) encryptUseDES:(NSString *)plainText
                         key:(NSString *)key
{
    
    NSError *error = nil;
    
    NSData *ordata = [plainText mj_JSONData];
    NSData *desdata = [ordata DESEncryptedDataUsingKey:key error:&error];
    NSString *desString = [[NSString alloc] initWithData:[GTMBase64 encodeData:desdata] encoding:NSUTF8StringEncoding];
    
    
    return desString;
    
    NSString *ciphertext = nil;
    const char *textBytes = [plainText UTF8String];
    NSUInteger dataLength = [plainText length];
    unsigned char buffer[dataLength];
    memset(buffer, 0, sizeof(char));
    Byte iv[] = {1,2,3,4,5,6,7,8};
    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,
                                          kCCOptionPKCS7Padding,
                                          [key UTF8String], kCCKeySizeDES,
                                          iv,
                                          textBytes, dataLength,
                                          buffer, 10240,
                                          &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
        
        ciphertext = [[NSString alloc] initWithData:[GTMBase64 encodeData:data] encoding:NSUTF8StringEncoding];
    }
    return ciphertext;
}


/**
 *  des + base 64 解密
 *
 *  @param cipherText 需要解密的内容
 *  @param key        密钥
 *
 *  @return 解密后的内容
 */
- (NSString *) decryptUseDES:(NSString*)cipherText
                         key:(NSString*)key
{
    NSError *error = nil;
    NSData* desdata = [GTMBase64 decodeString:cipherText];
    NSData * ordata = [desdata decryptedDESDataUsingKey:key error:&error];
    NSString *orString = [ordata mj_JSONString] ;
    return orString;
    
}
/**
 *  对模型进行加密
 *
 *  @param requestModel 请求模型
 *
 *  @return 返回加密后字典{
 */
-(NSDictionary*)baseCompress:(GJWBaseRequest*)requestModel operation:(GBNetToolOperation *)operation{
//    NSDictionary *paramters =  [self encryptWithDict:[requestModel dicttionaryOfparmaters]];
    
    NSString *jsonString = [self stringWithDictionary:[requestModel dicttionaryOfparmaters]];
    //des + base64 加密
    if (operation.encryptDES) {
        jsonString = [self encryptUseDES:jsonString key:DES_KEY];
    }
    NSData* requestData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    //压缩
    //    NSData* compressData = [ASIDataCompressor compressData:requestData error:nil];
    NSString* base64Str = [GTMBase64 stringByEncodingData:[requestData gzippedData]
                           ];
    //    NSLog(@"压缩转码处理后的请求%@",base64Str);
    NSDictionary *paramters = [NSDictionary  dictionaryWithObjectsAndKeys:base64Str,JSON_KEY, nil];
    return paramters;
}

///**
// *  对字典进行加密
// *
// *  @param dict 需要加密的字典
// *
// *  @return {data:xxxxxx}
// */
//-(NSDictionary*)encryptWithDict:(NSDictionary*)dict{
//
//    return paramters;
//}

//解密字典
-(NSDictionary*)decryptWith:(NSDictionary*)dict{
    NSString *enString = [dict objectForKey:JSON_KEY];
//    NSString *deString = [self decryptUseDES:enString key:DES_KEY];
    NSString *deString = [DesToHexString decrypt:[enString stringByReplacingOccurrencesOfString:@"\n" withString:@""] withKey:DES_KEY];
    //解密报文主体字典
    NSDictionary *bodyDict = [deString objectFromJSONString];
    return bodyDict;
}
#pragma mark - 缓存操作
/**
 *  缓存数据
 *
 *  @param urlStr   缓存的url
 *  @param paramers 缓存的原始数据
 */
-(void)cacheUrl:(NSString*)urlStr
       paramers:(NSDictionary*)paramers{
//    RspCacheDAO *dao = [[RspCacheDAO alloc]init];
//    RspCacheModel *ca = [[RspCacheModel alloc]init];
//    ca.requrlstr = urlStr;
//    
////    NSDictionary*cacheData =  [self encryptWithDict:paramers]; // 加密
//    ca.rspdata = [paramers mj_JSONData];
//    [dao insert:ca];
}
-(NSDictionary*)getCacheWithUrl:(NSString*)urlStr
                       paramers:(NSDictionary*)paramers{
//    RspCacheDAO *dao = [[RspCacheDAO alloc]init];
//    RspCacheModel *ca = [[RspCacheModel alloc]init];
//    ca.requrlstr = urlStr;
//    RspCacheModel *ca2 = [dao findById:ca];
//    if (ca2) {
//        NSDictionary *bodyDict = (NSDictionary*)[ca2.rspdata mj_JSONObject];
////        NSDictionary *retDict =  [self decryptWith:bodyDict];//解密
//        return bodyDict;
//    }
    return nil;
}
-(void)clearAllCache{
//    RspCacheDAO *dao = [[RspCacheDAO alloc]init];
//    [dao clearAllCache];
}
@end
